{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Contrarian view on closing files.\n",
    "It has become conventional wisdom to always explicitly close file-like objects, via context managers.\n",
    "The [google style guide](\n",
    "https://google.github.io/styleguide/pyguide.html#311-files-and-sockets)\n",
    "is representative:\n",
    "\n",
    "> Explicitly close files and sockets when done with them.\n",
    "Leaving files, sockets or other file-like objects open unnecessarily has many downsides, including:\n",
    "\n",
    "> They may consume limited system resources, such as file descriptors.\n",
    "  * Code that deals with many such objects may exhaust those resources unnecessarily if they're not returned to the system promptly after use.\n",
    "  * Holding files open may prevent other actions being performed on them, such as moves or deletion.\n",
    "  * Files and sockets that are shared throughout a program may inadvertantly be read from or written to after logically being closed. If they are actually closed, attempts to read or write from them will throw exceptions, making the problem known sooner.\n",
    "\n",
    "> Furthermore, while files and sockets are automatically closed when the file object is destructed, tying the life-time of the file object to the state of the file is poor practice, for several reasons:\n",
    "  * There are no guarantees as to when the runtime will actually run the file's destructor. Different Python implementations use different memory management techniques, such as delayed Garbage Collection, which may increase the object's lifetime arbitrarily and indefinitely.\n",
    "  * Unexpected references to the file may keep it around longer than intended (e.g. in tracebacks of exceptions, inside globals, etc).\n",
    "\n",
    "> The preferred way to manage files is using the \"with\" statement:\n",
    "```\n",
    "with open(\"hello.txt\") as hello_file:\n",
    "    for line in hello_file:\n",
    "        print line\n",
    "```\n",
    "\n",
    "## In theory\n",
    "Good points, and why limit this advice to file descriptors?  Any resource may be limited or require exclusivity;  that's why they're called resources.  Similarly one should always explicitly call `dict.clear` when finished with a `dict`.  After all, \"there are no guarantees as to when the runtime will actually run the <object's> destructor.  And \"code that deals with many such objects may exhaust those resources unnecessarily\", such as memory, or whatever else is in the `dict`.\n",
    "\n",
    "But in all seriousness, this advice is applying a notably higher standard of premature optimization to file descriptors than to any other kind of resource.  There are plenty of Python projects that are guaranteed to run on CPython for a variety of reasons, where destructors are immediately called.  And there are plenty of Python projects where file descriptor usage is just a non-issue.  It's now depressingly commonplace to see this in `setup.py` files:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"README.md\") as readme:\n",
    "    long_description = readme.read()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's consider a practical example: a `load` function which is supposed to read and parse data given a file path."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv\n",
    "import json\n",
    "\n",
    "def load(filepath):\n",
    "    \"\"\"the supposedly bad way\"\"\"\n",
    "    return json.load(open(filepath))\n",
    "\n",
    "def load(filepath):\n",
    "    \"\"\"the supposedly good way\"\"\"\n",
    "    with open(filepath) as file:\n",
    "        return json.load(file)\n",
    "\n",
    "def load(filepath):\n",
    "    \"\"\"with a different file format\"\"\"\n",
    "    with open(filepath) as file:\n",
    "        return csv.reader(file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Which versions work correctly?  Are you sure?  If it's not immediately obvious why one of these is broken, that's the point.  In fact, it's worth trying out before reading on.\n",
    "\n",
    "\n",
    "...\n",
    "\n",
    "\n",
    "The `csv` version returns an iterator over a closed file.  It's a violation of procedural abstraction to know whether the result of `load` is lazily evaluated or not; it's just supposed to implement an interface.  Moreover, according to this best practice, it's *impossible* to write the `csv` version correctly.  As absurd as it sounds, it's just an abstraction that can't exist.\n",
    "\n",
    "Defiantly clever readers are probably already trying to fix it.  Maybe like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load(filepath):\n",
    "    with open(filepath) as file:\n",
    "        yield from csv.reader(file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "No, it will not be fixed.  This version only appears to work by *not* closing the file until the generator is exhausted or collected.\n",
    "\n",
    "This trivial example has deeper implications.  If one accepts this practice, then one must also accept that storing a file handle anywhere, such as on an instance, is also disallowed.  Unless of course that object then virally implements it owns context manager, ad infinitum.\n",
    "\n",
    "Furthermore it demonstrates that often the context is not being managed locally.  If a file object is passed another function, then it's being used outside of the context.  Let's revisit the `json` version, which works because the file is fully read.  Doesn't a json parser have some expensive parsing to do after it's read the file?  It might even throw an error.  And isn't it desirable, trivial, [and likely](https://github.com/python/cpython/blob/master/Lib/json/__init__.py#L274) that the implementation releases interest in the file as soon as possible?\n",
    "\n",
    "So in reality there are scenarios where the supposedly good way could keep the file open *longer* than the supposedly bad way.  The original inline version does exactly what it's supposed to do: close the file when all interested parties are done with it.  Python uses garbage collection to manage shared resources.  Any attempt to pretend otherwise will result in code that is broken, inefficient, or reinventing reference counting.\n",
    "\n",
    "A true believer now has to accept that `json.load` is a useless and dangerous wrapper, and that the only correct implementation is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load(filepath):\n",
    "    with open(filepath) as file:\n",
    "        contents = file.read()\n",
    "    return json.loads(contents)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This line of reasoning reduces to the absurd: a file should never be passed or stored anywhere.  Next an example where the practice has caused real-world damage.  \n",
    "\n",
    "## In practice\n",
    "[Requests](https://requests.readthedocs.io/en/master/) is one of the most popular python packages, and [officially recommended](https://docs.python.org/3/library/http.client.html#module-http.client).  It includes a [Session](http://requests.readthedocs.org/en/latest/user/advanced/#session-objects) object which supports closing via a context manager.  The vast majority of real-world code uses the the top-level functions or single-use sessions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = requests.get(...)\n",
    "\n",
    "with requests.Session() as session:\n",
    "    response = session.get(...)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sessions manage the connection pool, so this pattern of usage is establishing a new connection every time.  There are popular standard API clients which seriously do this, for every single request to the same endpoint.\n",
    "\n",
    "Requests' documentation prominently states that \"Keep-alive and HTTP connection pooling are 100% automatic\".  So part of the blame may lay with that phrasing, since it's only \"automatic\" if sessions are reused.  But surely a large part of the blame is the dogma of closing sockets, and therefore sessions, explicitly.\n",
    "The whole point of a connection pool is that it may leave connections open, so users who genuinely need this granularity are working at the wrong abstraction layer.  `http.client` is already builtin for that level of control.\n",
    "\n",
    "Tellingly, requests' own top-level functions didn't always close sessions.  There's a long history to that code, including a [version that only closed sessions on success](https://github.com/kennethreitz/requests/commit/3155bc99362a8c6ab136b6a3bb999732617cd2e5).  An older version was [causing warnings](https://github.com/kennethreitz/requests/issues/1882), when run to check for such warnings, and was being blamed for the *appearance* of [leaking memory](https://github.com/kennethreitz/requests/issues/1685).  Those threads are essentially debating whether a resource pool is \"leaking\" resources.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Truce\n",
    "Prior to `with` being introduced in Python 2.5, it was *not* recommended that inlined reading of a file required a `try... finally` block.  Far from it, in the past idioms like `open(...).read()` and `for line in open(...)` were lauded for being succinct and expressive.  But if all this orphaned file descriptor paranoia was well-founded, it would have been a problem back then too.\n",
    "\n",
    "Finally, let's address readability.  It could be argued (though it rarely is) that showing the reader when the file is closed has inherent value.  Conveniently, that tends to align with having opened the file for writing anyway, thereby needing an reference to it.  In which case, the readability is approximately equal, and potential pitfalls are more realistic.  But readability is genuinely lost when the file would have been opened in a inline expression.\n",
    "\n",
    "The best practice is unjustifiably special-casing file descriptors, and not seeing its own reasoning through to its logical conclusion.  This author proposes advocating for _anonymous read-only_ `open` expressions.  Your setup script is not going to run out of file descriptors because you wrote `open(\"README.md\").read()`."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.8.3 64-bit",
   "language": "python",
   "name": "python_defaultSpec_1593981339098"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "nikola": {
   "category": "style",
   "date": "2020-07-05",
   "description": "",
   "link": "",
   "slug": "closing-files",
   "tags": "",
   "title": "Closing files",
   "type": "text"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}